﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace Marmat.Forms
{
    public class BindingFieldUITypeEditor : UITypeEditor
    {
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.Modal;
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            BindingField bindingField = value as BindingField;
            IWindowsFormsEditorService edsvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
            if (edsvc != null)
            {
                Marmat.Forms.Design.BindingEditorForm frm = new Design.BindingEditorForm(context.Instance as Control, bindingField);
                DialogResult dialog = frm.ShowDialog();
                if (dialog == DialogResult.OK)
                {
                    if (frm.TreeList1.FocusedNode != null && frm.TreeList2.FocusedNode != null)
                    {
                        bindingField.DataSource = frm.TreeList1.FocusedNode.Tag as IBindingSource;
                        bindingField.DataMember = frm.TreeList2.FocusedNode.GetValue("Name").ToString();
                        context.OnComponentChanged();
                    }
                }
                else if (dialog == DialogResult.Retry)
                {
                    bindingField.DataSource = null;
                    bindingField.DataMember = null;
                    context.OnComponentChanged();
                }
            }
            return value;
        }

        public override bool GetPaintValueSupported(ITypeDescriptorContext context)
        {
            return false;
        }
    }
}
